<template>
    <div class="permission-container">
        <div class="page-header">
            <div class="header-content">
                <div class="title-section">
                    <div class="title-text">
                        <h1 class="page-title">权限管理</h1>
                    </div>
                </div>
                <div class="header-actions">
                    <el-button type="primary" size="large" @click="dialogFormVisible = true" class="primary-btn">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新增权限
                    </el-button>
                </div>
            </div>
        </div>

        <div class="card search-card">
            <div class="card-header">
                <h3 class="card-title">
                    <el-icon>
                        <Search />
                    </el-icon>
                    搜索条件
                </h3>
            </div>
            <el-form :inline="true" :model="formInline" class="search-form">
                <el-form-item label="权限名称">
                    <el-input v-model="formInline.PermissionName" placeholder="请输入权限名称" clearable size="large"
                        style="width: 300px;" class="custom-input" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="large" @click="onSubmit" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button size="large" @click="resetSearch" class="reset-btn">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card table-card">
            <div class="card-header">
                <div class="table-actions">
                    <el-button size="small" @click="refreshTable" class="refresh-btn">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        刷新
                    </el-button>
                </div>
            </div>
            <el-table :data="tableData" style="width: 100%"
                :header-cell-style="{ background: '#f3f4f6', color: '#374151' }" border stripe class="custom-table">
                <el-table-column fixed type="index" label="序号" width="80" align="center" />
                <el-table-column prop="permissionName" label="权限名" min-width="150" />
                <el-table-column prop="permissionURL" label="权限路由" min-width="200" />
                <el-table-column prop="number" label="权限序号" width="120" align="center" />
                <!-- 新增树形控件 -->
                <div class="tree-section">
                    <h4 style="margin: 16px 0 8px 0;">权限树</h4>
                    <el-tree :data="treeData" :props="treeProps" node-key="id" highlight-current default-expand-all
                        style="background: #fff; border-radius: 8px; padding: 12px;" />
                </div>
                <el-table-column fixed="right" label="操作" width="180" align="center">
                    <template v-slot="hh">
                        <el-button link type="primary" size="small" @click="handleClicks(hh.row)" class="edit-btn">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button link type="danger" size="small" @click="handleClick(hh.row.id)" class="delete-btn">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="page.Index" v-model:page-size="page.Size"
                    :page-sizes="[3, 5, 10, 50]" :size="size" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="page.TotaCount" prev-text="上一页"
                    next-text="下一页" class="custom-pagination" />
            </div>
        </div>
    </div>

    <el-dialog v-model="dialogFormVisible" title="新增权限" width="600" class="custom-dialog permission-dialog">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
            <el-form-item label="权限名称" prop="permissionName">
                <el-input v-model="ruleForm.permissionName" placeholder="请输入权限名称" class="dialog-input" />
            </el-form-item>

            <el-form-item label="权限路由" prop="permissionURL">
                <el-input v-model="ruleForm.permissionURL" placeholder="请输入权限路由" class="dialog-input" />
            </el-form-item>

            <el-form-item label="权限序号" prop="number">
                <el-input-number v-model="ruleForm.number" :min="1" placeholder="请输入权限序号" style="width: 100%;"
                    class="dialog-input" />
            </el-form-item>
            <el-form-item label="权限序号">
                <!-- 新增树形控件 -->
                <div class="tree-section">
                    <el-tree :data="treeData" :props="treeProps" node-key="id" highlight-current default-expand-all
                        style="background: #fff; border-radius: 8px; padding: 12px;"
                        @node-click="handleTreeNodeClick" />
                </div>
            </el-form-item>


            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)" class="submit-btn">
                    <el-icon>
                        <Check />
                    </el-icon>
                    提交
                </el-button>
                <el-button @click="resetForm(ruleFormRef)" class="reset-btn">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="dialogFormVisibles" title="编辑权限" width="600" class="custom-dialog permission-dialog">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
            <el-form-item label="权限名称" prop="permissionName">
                <el-input v-model="ruleForm.permissionName" placeholder="请输入权限名称" class="dialog-input" />
            </el-form-item>

            <el-form-item label="权限路由" prop="permissionURL">
                <el-input v-model="ruleForm.permissionURL" placeholder="请输入权限路由" class="dialog-input" />
            </el-form-item>

            <el-form-item label="权限序号" prop="number">
                <el-input-number v-model="ruleForm.number" :min="1" placeholder="请输入权限序号" style="width: 100%;"
                    class="dialog-input" />
            </el-form-item>

            <el-form-item label="权限序号">
                <!-- 新增树形控件 -->
                <div class="tree-section">
                    <el-tree :data="treeData" :props="treeProps" node-key="id" highlight-current default-expand-all
                        style="background: #fff; border-radius: 8px; padding: 12px;"
                        @node-click="handleTreeNodeClick" />
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForms(ruleFormRef)" class="submit-btn">
                    <el-icon>
                        <Check />
                    </el-icon>
                    修改
                </el-button>
                <el-button @click="resetForms(ruleFormRef)" class="reset-btn">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
//分页
import type { ComponentSize } from 'element-plus'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, List, Edit, Delete, Check, Key } from '@element-plus/icons-vue'
import { axiosr } from '@/http/axiosRead'
import { axiosw } from '@/http/axiosWrtie'


const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const formInline = reactive({
    PermissionName: ''
})
const dialogFormVisible = ref(false)
const dialogFormVisibles = ref(false)
const page = reactive({
    Index: 1,
    Size: 3,
    TotaCount: 0,
    TotaPage: 0
})

const onSubmit = () => {
    show()
}

const resetSearch = () => {
    formInline.PermissionName = ''
    page.Index = 1
    show()
}

const refreshTable = () => {
    show()
}

const handleClicks = (data: any) => {
    dialogFormVisibles.value = true
    ruleForm.id = data.id
    ruleForm.permissionName = data.permissionName
    ruleForm.permissionURL = data.permissionURL
    ruleForm.parentId = data.parentId
    ruleForm.number = data.number
}

//删除
const handleClick = (id: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        'error',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            axiosw.delete('/Permission/DeletePermission', {
                params: {
                    Id: id
                }
            }).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    show()
                    dialogFormVisible.value = false
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            })
        })
}

const tableData = ref([])
// 在 script 部分添加以下接口定义
interface TreeNode {
    id: string | number
    name: string
    children?: TreeNode[]
}

// 修改 treeData 的定义
const treeData = ref<TreeNode[]>([])
const treeProps = {
    label: 'name',
    children: 'children',
}
const fetchTree = () => {
    axiosr.get('/Permission/GetPermissionsFromDatabaseTree').then(res => {
        // 递归处理children为对象数组
        function normalize(arr: any[]): any[] {
            return arr.map(item => {
                let children = []
                if (Array.isArray(item.children) && item.children.length > 0 && typeof item.children[0] === 'string') {
                    children = item.children.map((name: string, idx: number) => ({
                        id: `${item.id}-${idx}`,
                        name: name,
                        children: []
                    }))
                } else if (Array.isArray(item.children)) {
                    children = normalize(item.children)
                }
                return {
                    ...item,
                    children: children.length ? children : undefined
                }
            })
        }
        treeData.value = normalize(res.data.data || [])
    })
}

const show = () => {
    axiosr.get('/Permission/GetPermission', {
        params: {
            PermissionName: formInline.PermissionName,
            Index: page.Index,
            Size: page.Size
        }
    }).then((res) => {
        tableData.value = res.data.pageData
        page.TotaCount = res.data.totaCount
        page.TotaPage = res.data.totaPage
    })
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "id": 0,
    "permissionName": "",
    "permissionURL": "",
    "parentId": 0 as number | string,
    "number": null
})


const rules = reactive<FormRules>({
    permissionName: [
        { required: true, message: '不能为空!', trigger: 'blur' },
    ],
    permissionURL: [
        { required: true, message: '不能为空!', trigger: 'blur' },
    ],
    number: [
        { required: true, message: '不能为空!', trigger: 'blur' },
    ],
})
//提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    Number(ruleForm.parentId)
    await formEl.validate((valid, fields) => {
        if (valid) {
            axiosw.post('/Permission/AddPermission', ruleForm).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    show()
                    dialogFormVisible.value = false
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisible.value = false
}


//修改
const submitForms = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    Number(ruleForm.parentId)
    await formEl.validate((valid, fields) => {
        if (valid) {
            axiosw.put('/Permission/UpdatePermission', ruleForm).then((res) => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg)
                    show()
                    dialogFormVisibles.value = false
                }
                else {
                    ElMessage.error(res.data.msg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 你的 ruleForm 已经定义
const handleTreeNodeClick = (data: TreeNode) => {
    ruleForm.parentId = data.id
    ElMessage.success('上级权限是'+data.name)
}
//重置
const resetForms = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormVisibles.value = false
}

onMounted(() => {
    show()
    fetchTree()
})

watch(page, () => {
    show()
}, { deep: true })
</script>

<style scoped>
/* 卡片化背景 */
:deep(.el-table),
:deep(.el-form),
:deep(.el-dialog),
:deep(.el-pagination) {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(59, 130, 246, 0.08);
}

/* 搜索栏样式 */
:deep(.el-form) {
    padding: 18px 18px 0 18px;
    margin-bottom: 12px;
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 2px 12px rgba(59, 130, 246, 0.08);
    display: flex;
    align-items: center;
}

:deep(.el-form .el-form-item) {
    margin-right: 16px;
    margin-bottom: 0;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    background: #f6f8fa;
}


:deep(.el-button--primary:hover) {
    background: #1e40af;
}

:deep(.el-button) {
    border-radius: 8px;
}

/* 表格样式 */
:deep(.el-table) {
    border-radius: 16px;
    overflow: hidden;
    font-size: 15px;
}

:deep(.el-table th) {
    background: #f6f8fa !important;
    color: #222 !important;
    font-weight: bold;
    height: 48px;
}

:deep(.el-table td) {
    height: 44px;
}

:deep(.el-table__row) {
    transition: background 0.2s;
}

:deep(.el-table__row:hover) {
    background: #f0f6ff;
}

:deep(.el-switch__core) {
    height: 22px !important;
    min-width: 40px !important;
}

:deep(.el-switch.is-checked .el-switch__core) {
    background: #2563eb !important;
}

:deep(.el-switch__action) {
    width: 18px !important;
    height: 18px !important;
}

/* 操作按钮icon */
:deep(.el-button--text),
:deep(.el-button.is-link) {
    color: #2563eb !important;
    font-size: 18px;
    padding: 0 6px;
}

:deep(.el-button--text:hover),
:deep(.el-button.is-link:hover) {
    background: #f0f6ff;
}

/* 分页样式 */
:deep(.el-pagination) {
    padding: 12px 0 0 0;
    background: transparent;
    text-align: right;
}

:deep(.el-pagination .el-pager li.is-active) {
    background: #2563eb;
    color: #fff;
    border-radius: 6px;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 6px;
}
</style>
